<template>
    <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <el-input
            clearable
            v-model="listQuery.sectionNo"
            :style="searchInputStyle"
            class="filter-item"
            placeholder="请输入工段编号"
      ></el-input>
      <el-input
            clearable
            v-model="listQuery.machineId"
            :style="searchInputStyle"
            class="filter-item"
            placeholder="请输入机台编号"
      ></el-input>
      <el-input
            clearable
            v-model="listQuery.machineType"
            :style="searchInputStyle"
            class="filter-item"
            placeholder="请输入机台类型"
      ></el-input>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
    </div>

    <!-- table 表格 -->
    <el-table ref="multipleTable" @selection-change="handleSelectionChange" :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%">
      <el-table-column  type="selection" width="55"/>
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="机台类型"  prop="machineType"   align="center"/>
      <el-table-column label="机台编号"  prop="machineId"   align="center"/>
      <el-table-column  label="部门" prop='department' align="center" width="100px"/>
      <el-table-column  label="职级" prop='jobClass' align="center"/>
      <el-table-column  label="工段编号" prop='sectionNo' align="center"/>
      <el-table-column  label="操作" align="center" width="120">
        <template slot-scope="scope" >
              <el-button size="mini" type="primary" @click="handleEdit(scope.row)">添加工单</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px" v-if="multipleSelection.length">
      <el-button  type="primary" @click="toggleOrder">批量机台添加工单</el-button>
      <el-button @click="toggleSelection">取消选择</el-button>
    </div>
   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>


      <el-divider></el-divider>
      <el-button type="success" size="small" @click="getExcelList">下载Excel模板</el-button>
      <el-divider></el-divider>
      <!-- 上传Excel表单 -->
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="action"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :headers="httpHeader"
        :file-list="fileList"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取工单文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload" :loading="upLoading">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">将Excel表单从此处上传到服务器</div>
      </el-upload>

    </div>

        <!-- 添加工单弹出表单 -->
    <el-dialog title="添加工单" :visible.sync="dialogFormVisible" width="700px">
    <el-form :model="modifyform" v-infinite-scroll="load">
      <el-form-item label="工段编号" :label-width="formLabelWidth" v-if="!multipleSelection.length">
        <el-input v-model="modifyform.sectionNo" :disabled="true" style="width:400px"/>
      </el-form-item>
      <el-form-item label="机器编号" :label-width="formLabelWidth" v-if="!multipleSelection.length">
        <el-input v-model="modifyform.machineId" :disabled="true" style="width:400px" />
      </el-form-item>
      <el-form-item label="机器名称" :label-width="formLabelWidth" v-if="!multipleSelection.length">
        <el-input v-model="modifyform.machineName" :disabled="true" style="width:400px" />
      </el-form-item>
      <el-form-item label="机台类型" :label-width="formLabelWidth" v-if="!multipleSelection.length">
        <el-select v-model="modifyform.machineType" :disabled="true" placeholder="请选择机台类型" style="width:400px">
          <el-option :value="item" :label="item" v-for="(item,index) in this.belongList" :key="index"/>
        </el-select>
      </el-form-item>

      <el-form-item
        v-for="(domain,index) in domains"
        :label="'工单信息'"
        :key="domain.key"
        prop="domain.deviceBarcode"
        :rules="{ required: true,message: '请输入工单条码',trigger: 'blur' }"
        :label-width="formLabelWidth">

        <el-input
          clearable
          v-model="domain.deviceBarcode"
          placeholder="请输入工单条码(格式例如:5103-2204210070-0010)"
          style="width:400px;margin-top:10px;"
          @change="devicechange(index)"
          ></el-input>

        <el-button @click.prevent="removeDomain(domain)">删除</el-button>

        <div class="demonstration" v-if="!domain.deviceBarcode || domain.status">{{domain.msgdevice}}</div>

        <el-date-picker
          v-model="domain.beginTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="请选择工单开始日期"
          format="yyyy-MM-dd HH"
          value-format="yyyy-MM-dd HH:mm:ss"
          popper-class="tpc"
          end-placeholder="结束日期"
          style="width: 400px;margin-top:10px;">
        </el-date-picker>
        <div class="demonstration" v-if="!domain.beginTime">请选择工单开始日期-结束日期</div>
        <el-input
          clearable
          v-model="domain.count"
          placeholder="请输入零件数"
          class="l-input"></el-input>
        <div class="demonstration" v-if="!domain.count">请输入零件数</div>

        <div style="margin-top:10px;">
          <el-input-number size="mini" v-model="domain.upperLimit" :min="1" :max="3" ></el-input-number>
          <span class="form-num">（设置人数上限）</span>
        </div>

      </el-form-item>

      <div>

      </div>
      <el-form-item label="" :label-width="formLabelWidth">
        <el-button @click="addDomain">新增工单</el-button>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel()">取 消</el-button>
      <el-button type="primary" @click="submitForm()">确 定</el-button>
    </div>
    </el-dialog>

  </div>
</template>

<script>
import { machinePage } from '../../api/machine'
import { insPlanMachine } from '../../api/orderAndMachine'
import {uploadURL} from '@/utils/baseURL'
import { getToken } from '@/utils/auth'
export default {
    name: 'orderAndMachine',
    data () {
        return {
          fileList:[],
          action: uploadURL + '/back/planMachine/processExcelMachine',
            listQuery: {
                sectionNo: '',                              //工段编号
                machineId: '',                              //机台号
                machineType: '',
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            modifyform: {
                sectionNo: '',                              //工段编号
                machineId: '',                              //机台号
                machineName: '',                            //机台名
                jobClass: '',                                //职级
                machineType: '',                           //机台类型
            },
            formLabelWidth: '100px',
            searchInputStyle: 'width: 150px;margin-right:15px;',
            total: 0,                                      //数据的总数
            tableInfo: [],
            dialogFormVisible: false,
            belongList:['装配','数冲','折弯','钳铆','人工焊组','机器人组','打磨组','喷涂一线','喷涂二线','喷涂三线','喷涂样品线','走芯机','CNC','其他'],
            loadingList: false,
            domains: [{
              deviceBarcode: '',
              beginTime: '',
              finishTime: '',
              count: '',
              msgdevice: '请输入工单条码',
              status: 0,
              upperLimit: 3
            }],
            load: true,
            idlist: [],
            times: 0,
            httpHeader: {
            'Authorization': ''
            },
            multipleSelection: [],
            upLoading: false,
            userInfo: this.$store.state.user.userInfo,
        }
    },
    methods: {
        removeDomain(item) {
          var index = this.domains.indexOf(item)
          if (index !== -1) {
            this.domains.splice(index, 1)
          }
        },
        addDomain() {
          this.domains.push({
            deviceBarcode: '',
            beginTime: '',
            finishTime: '',
            upperLimit: 3,
            count: '',
            msgdevice: '请输入工单条码',
            status: 0
          });
        },
      clearData(){
        this.listQuery.page = 1
        this.listQuery.limit = 10
      },
      getData(){
        this.clearData()
        this.handleFilter()
      },
        async handleFilter() {
          this.loadingList = true
          let query = Object.assign({},this.listQuery)
          let {data} = await machinePage(query)
          this.total = data.total
          this.tableInfo = data.records
          this.loadingList = false
        },
        handleEdit(item) {
          this.modifyform = Object.assign({},item)
          this.dialogFormVisible = true
          this.toggleSelection()
          console.log(this.modifyform)
        },
        // 将弹框新增工单信息传入后台，并且消息提示是否新增成功
        async modifyMachine(item,index) {
          const data = await insPlanMachine(item)
          this.times++
          if(data.code == '1'){
          } else {
            this.idlist.push(index)
            this.domains[index].msgdevice = data.msg.split('！')[1]
            this.domains[index].status = 1
          }
          if(this.times == this.domains.length) {
            let domains = this.domains?JSON.parse(JSON.stringify(this.domains)):[]
            this.domains = domains.filter((item,idx)=>{
              return this.idlist.includes(idx)
            })
            this.times = 0
            if(this.domains.length){
              this.idlist = []
              this.$confirm(data.msg, '警告！', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                showCancelButton: false,
                type: 'warning'
              })
              // this.$message({
              //   type: 'error',
              //   message: data.msg
              // })
            } else {
              this.idlist = []
              this.dialogFormVisible = false
              this.$message({
                type: 'success',
                message: '操作成功！'
              })
            }
          }
        },
        // 每条工单请求一次接口
      addOrderToMachine() {
        let query = JSON.parse(JSON.stringify(this.domains))
        query.forEach((item,index) => {
          let dateTime = JSON.parse(JSON.stringify(item.beginTime))
          delete item.msgdevice
          delete item.status
          item.beginTime = dateTime[0]
          item.finishTime = dateTime[1]
          item.machineId = this.modifyform.machineId
          this.modifyMachine(item,index)
        })
      },
      // 提交表单之前先进行验证
      submitForm() {
        let query = JSON.parse(JSON.stringify(this.domains))
        if(!query.length) return this.$message({
          message: '请添加工单',
          type: 'warning'
        })
        query.forEach((item,index) => {
          if(!item.deviceBarcode || !item.beginTime || !item.count) return this.$message({
            message: '请先完善工单信息',
            type: 'warning'
          })
          if(index+1 ==query.length) {this.addOrderToMachine()}
        })
      },
      devicechange(index) {
        this.domains[index].status = 0
        this.domains[index].msgdevice = '请输入工单条码'
      },
      cancel(){
        this.dialogFormVisible = false
        this.idlist = []
      },
      // table表单下方的页码组件改变每页显示的数据条数
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.handleFilter()
      },
      // table表单下方的页码组件改变页面
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.handleFilter()
      },
      handleSuccess(response) {
        console.log(response,'response')
        const result = response.code
        const errMsg = response.msg
          if(result == '1'){
              this.$message({
                type: 'info',
                message: errMsg
            })
            this.handleFilter()
          }else{
              this.$confirm(errMsg, '警告！', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                showCancelButton: false,
                type: 'warning'
              })
              // this.$message({
              //   type: 'warning',
              //   message: errMsg
              // })
          }
          this.upLoading = false
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      toggleOrder() {
        let machineIdList = []
        this.multipleSelection.forEach(items=>{
          machineIdList.push(items.machineId)
        })
        let obj = {}
        obj.machineId = machineIdList.join(',')
        this.modifyform = Object.assign({},obj)
        console.log(this.modifyform)
        this.dialogFormVisible = true
      },
      // 取消选择
      toggleSelection() {
        this.$refs.multipleTable.clearSelection();
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      submitUpload() {
        // this.httpHeader.Authorization = this.dealCookie(document.cookie)
        this.httpHeader.Authorization = getToken()
        this.upLoading = true
        this.$refs.upload.submit()
        // setTimeout(this.handleFilter(), 2000)
      },
      // cookies的处理函数
      dealCookie(value) {
          const cookieArr = value.split('=')
          console.log(value,cookieArr)
          // 测试服使用cookieArr[2]
          return cookieArr[1]
      },
      // 下载模板表单
      getExcelList() {
        window.open('http://180.76.113.62:8110/image/portrait/example1.rar')
      },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>
.l-input{
  width: 400px;
  margin-top: 10px;
}
.tpc .el-time-spinner__wrapper {
  width:100% !important;
}
.tpc .el-scrollbar:nth-of-type(2) {
  display: none !important;
}
.border{
  border-color: #F56C6C !important;
}
.demonstration{
  font-size: 12px;
  color: #F56C6C;
}
.form-num{
  font-size: 12px;
  margin-right: 10px;
}
</style>
